#include "capturewidget.h"
#include "core/controller.h"

CaptureWidget::CaptureWidget(const uint id, const QString &savePath, bool fullScreen, QWidget *parent):
    QWidget(parent),
    m_mouseOverHandle(SelectionWidget::NO_SIDE),
    m_mouseOverHandleCamera(CameraPage::NO_SIDE),
    m_toolBar(nullptr),
    m_cutdown(nullptr),
    m_showKeyController(nullptr),
    m_clickAnimateControl(nullptr),
    m_id(id)
{
    isHoverWidow = false;
    isfirstPress = false;
    isfirstRelease = false;
    isMousePress = false;
    isMouseRelease = false;
    isMove = false;
    isSize = false;
    m_uiColor = QColor::fromRgbF(0.0980392, 0.0980392, 0.0980392, 1.0);
    m_opacity = 100;

    setAttribute(Qt::WA_X11DoNotAcceptFocus, true);
    setAttribute(Qt::WA_AlwaysShowToolTips);        //始终显示工具提示
    setAttribute(Qt::WA_TranslucentBackground);     //实现背景透明
//    setAttribute(Qt::WA_DeleteOnClose);             //关闭时删除小部件
    setMouseTracking(true); //启用鼠标跟踪
    //初始化
    initSelection();
    size_label = new QLabel(this);
    size_label->setFixedSize(82, 24);
    size_label->hide();
    size_label->setAlignment(Qt::AlignCenter);
    QString str = "QLabel {"
          "border-width: 0px; "
          "border-radius: 4px; "
          "background-color:rgba(225,225,225,180);"
          "font-size: 15px;"
          "color: black}";
    size_label->setStyleSheet(str); //Fix 样式表设置
    m_toolBar = new ToolBar(this);
    m_toolBar->hide();
    updateCursor();
    initConnect();
    //更新屏幕区域信息
    updateScreenRegions();
    //更新窗口信息
    auto screenNumber = QApplication::desktop()->screenNumber();
    QScreen *screen = QApplication::screens()[screenNumber];
    m_scale = screen->devicePixelRatio();

    if(!m_info.isWlcom()){
        setWindowFlags(Qt::BypassWindowManagerHint|
                       Qt::WindowStaysOnTopHint|
                       Qt::FramelessWindowHint
                       | Qt::Tool
                       );

    }else{
        setWindowFlags(Qt::FramelessWindowHint);
        KWindowSystem::setType(winId(), NET::OnScreenDisplay);
    }

    if (fullScreen) {
    QRect full_Rect = QGuiApplication::primaryScreen()->virtualGeometry();
    resize(full_Rect.size());
    }

    if (m_info.waylandDectected())
    {
        WindowManager::self();
        QPushButton *btn = new QPushButton(this);
        btn->setVisible(false);
        connect(btn, &QPushButton::clicked, this,[=](){
            QList<WindowId> lists = WindowManager::windows();
            for (auto windowId : lists){
                getWindow(windowId);
            }
        });
        btn->click();

        connect(WindowManager::self(),&WindowManager::windowAdded,this,[=](const WindowId& windowId){
            getWindow(windowId);
        });
    }
    else
    {
        QList<WId> windows = KWindowSystem::stackingOrder();    // 当前窗口活跃状态存储窗口ID
        for (WId id: windows) {
            KWindowInfo info(id, NET::WMState);                 // 判断窗口是否在处在激活状态
            KWindowInfo desktop_info(id, NET::WMDesktop);       // 判断窗口是否在当前截图桌面
            if (false == info.hasState(NET::Hidden) & desktop_info.isOnCurrentDesktop()) { // 判断窗口是否显示
                KWindowInfo info2(id, NET::WMFrameExtents);
                QRect rect(info2.frameGeometry().x() / m_scale,
                           info2.frameGeometry().y() / m_scale,
                           info2.frameGeometry().width() / m_scale,
                           info2.frameGeometry().height() / m_scale);
                rects.append(rect);
                mapRectToWindowId.insert(rect, id);
            }
        }
    }
}

CaptureWidget::~CaptureWidget()
{
    if (m_clickAnimateControl)
    {
        if(!m_info.isWlcom()){
            m_clickAnimateControl->pointerOnOff(false);
        }
        m_clickAnimateControl->deleteLater();
    }
}

void CaptureWidget::paintEvent(QPaintEvent * e)
{
    QPainter painter(this);
    QColor overlayColor(0, 0, 0, m_opacity);
    painter.setBrush(overlayColor);
    QRect r;
    if (m_selection->isVisible()) {
        r = m_selection->geometry().normalized().adjusted(0, 0, -1, -1);
    }
    QRegion grey(rect());
    grey = grey.subtracted(r);

    painter.setClipRegion(grey);
    painter.drawRect(-1, -1, rect().width() + 1, rect().height() + 1);
    painter.setClipRect(rect());
    QFont ft;
    ft.setPointSize(10);
    updateSizeLabelOption();
    painter.setRenderHint(QPainter::Antialiasing);

    if (m_selection->isVisible()) {
        m_toolBar->setProperty("useSystemStyleBlur", true);
        painter.setOpacity(0.6);
        painter.setPen(m_uiColor);
        // 绘制选框边框和手柄。
        updateSelectionBorder(painter);
    }

    QWidget::paintEvent(e);
}

void CaptureWidget::mousePressEvent(QMouseEvent * e)
{
    if (!(m_info.waylandDectected() && !m_info.isHWWayland() && (m_info.windowManager() == DesktopInfo::UKUI)))
    {
        showFullScreen();
    }
    update();
    if (e->button() == Qt::RightButton) {
        return;
    }

    if (e->button() == Qt::LeftButton) {
        isMousePress = true;
        m_dragStartPoint = e->pos();

        //点击按钮关闭摄像头
        if(m_camera && m_camera->isVisible()){
            if(m_button->geometry().contains(e->pos())){
                Controller::getInstance()->CloseCamerafromSetting();
            }
        }

        if (!isfirstPress) {
//            qDebug()<<"Press 第一次按下 确定框选区域/窗口";
            Controller::getInstance()->hideLeadWid();
            isfirstPress = true;
            isHoverWidow = true;
        }
        else if (m_mouseOverHandle == SelectionWidget::NO_SIDE
                 && m_selection->geometry().contains(e->pos())) {
            qDebug()<<"Press 选框按压移动";
            if (m_cutdown && !m_cutdown->isHidden()) {
                isMove = false;
            } else {
                isMove = true;
            }
            if (m_camera && m_camera->isVisible() && m_camera->geometry().contains(e->pos())){
                isMoveCamera = true;
            }
            if (m_camera && m_camera->isVisible() && m_mouseOverHandleCamera != CameraPage::NO_SIDE ){
                isSizeCamera = true;
            }
        }
        else if(m_mouseOverHandle != SelectionWidget::NO_SIDE){
//           qDebug()<<"Press 调节大小";
            if (m_cutdown && !m_cutdown->isHidden()) {
                isSize = false;
            } else {
                isSize = true;
            }
        }
        else if(!m_selection->geometry().contains(e->pos())
                && m_mouseOverHandle == SelectionWidget::NO_SIDE){
//            qDebug()<<"Press 点击工具栏或选框外";
            isSelectOut = true;
        }
       m_selection->saveGeometry();
       m_selection->setVisible(true);
       isMouseRelease = false;
       if(m_camera && m_camera->isVisible()){
           m_camera->saveGeometry();
       }
    }

    updateCursor();
}

void CaptureWidget::mouseMoveEvent(QMouseEvent * e)
{
    if (!m_dragStartPoint.isNull() &&
            (e->pos() - m_dragStartPoint).manhattanLength() < QApplication::startDragDistance()) {
        return; // 忽略微小移动
    }

    m_mousePos = e->globalPos();
    if(m_camera && m_camera->isVisible()){
        if(m_camera->geometry().contains(m_mousePos) ||
            m_button->geometry().contains(m_mousePos)){
            m_button->show();
        }else{
            m_button->hide();
        }
    }
    if (isfirstPress) {
        if (!isfirstRelease) {
//            qDebug()<<"按压后第一次移动";
            isHoverWidow = false;
            m_selection->setVisible(true);
            m_selection->setGeometry( QRect(m_dragStartPoint, m_mousePos).normalized());
            update();
        }else if (isMousePress) {

            if (isMove && !isMoveCamera && !isSizeCamera && m_mouseOverHandle == SelectionWidget::NO_SIDE ) {
//                qDebug()<<"移动整个选框";

                QRect initialRect = m_selection->savedGeometry().normalized();
                QPoint newTopLeft = initialRect.topLeft() + (e->pos() - m_dragStartPoint);
                QRect finalRect(newTopLeft, initialRect.size());

                if (finalRect.left() < rect().left() / m_scale) {           // rect()是物理坐标
                    finalRect.setLeft(rect().left() / m_scale);
                } else if (finalRect.right() > rect().right() / m_scale) {
                    finalRect.setRight(rect().right() / m_scale);
                }
                if (finalRect.top() < rect().top() / m_scale) {
                    finalRect.setTop(rect().top() / m_scale);
                } else if (finalRect.bottom() > rect().bottom() / m_scale) {
                    finalRect.setBottom(rect().bottom() / m_scale);
                }
                m_selection->setGeometry(finalRect.normalized().intersected(rect()));
                m_selectionRec = m_selection->geometry();
                m_selection->setSelectionChanged(true);
                m_toolBar->hide();
                update();
            }else if(isMoveCamera && m_mouseOverHandleCamera == CameraPage::NO_SIDE ){
                updateCameraPos(e->pos());

            }else if(isSize){
                // 通过手柄改变选框大小

                QRect r = m_selection->savedGeometry();
                QPoint offset = e->pos() - m_dragStartPoint;
                bool symmetryMod = qApp->keyboardModifiers() & Qt::ShiftModifier;
                using sw = SelectionWidget;
                if (m_mouseOverHandle == sw::TOPLEFT_SIDE
                    || m_mouseOverHandle == sw::TOP_SIDE
                    || m_mouseOverHandle == sw::TOPRIGHT_SIDE) {             // dragging one of the top handles
                    r.setTop(r.top() + offset.y());
                    if (symmetryMod) {
                        r.setBottom(r.bottom() - offset.y());
                    }
                }
                if (m_mouseOverHandle == sw::TOPLEFT_SIDE
                    || m_mouseOverHandle == sw::LEFT_SIDE
                    || m_mouseOverHandle == sw::BOTTONLEFT_SIDE) {             // dragging one of the left handles
                    r.setLeft(r.left() + offset.x());
                    if (symmetryMod) {
                        r.setRight(r.right() - offset.x());
                    }
                }
                if (m_mouseOverHandle == sw::BOTTONLEFT_SIDE
                    || m_mouseOverHandle == sw::BOTTON_SIDE
                    || m_mouseOverHandle == sw::BOTTONRIGHT_SIDE) {             // dragging one of the bottom handles
                    r.setBottom(r.bottom() + offset.y());
                    if (symmetryMod) {
                        r.setTop(r.top() - offset.y());
                    }
                }
                if (m_mouseOverHandle == sw::TOPRIGHT_SIDE
                    || m_mouseOverHandle == sw::RIGHT_SIDE
                    || m_mouseOverHandle == sw::BOTTONRIGHT_SIDE) {             // dragging one of the right handles
                    r.setRight(r.right() + offset.x());
                    if (symmetryMod) {
                        r.setLeft(r.left() - offset.x());
                    }
                }
                m_selection->setGeometry(r.intersected(rect()).normalized());
                m_selectionRec = m_selection->geometry();
                m_selection->setSelectionChanged(true);
                m_toolBar->hide();
                update();
            }else if(isSizeCamera){
//                qDebug()<<"摄像头 调节大小";
                updateCameraSize(e->pos());
            }

        }else{
            if (!m_selection->isVisible()) {
                m_toolBar->hide();
                return;
            }

            m_mouseOverHandle = m_selection->getMouseSide(m_mousePos);
            if(m_camera){
                m_mouseOverHandleCamera = m_camera->getMouseSide(m_mousePos);
            }
            updateCursor();
        }

    }else {
//            qDebug()<<"第一次按压前移动-选窗口（窗口截图）";
            for (QRect const rect : rects) {
                if (rect.contains(e->pos())) {
                    m_selection->setGeometry(rect);
                    m_selection->setVisible(true);
                }
            }
    }
}

void CaptureWidget::mouseReleaseEvent(QMouseEvent * e)
{
    if (Qt::LeftButton == e->button()) {
        if (!isfirstRelease) {
//            qDebug()<<"第一次释放 ";
            isfirstRelease = true;
            m_selectionRec = m_selection->geometry();

            if (isHoverWidow) {
                if(areas.contains(m_selectionRec)){
                    qDebug()<<"录制源 ： hover全屏 "<<m_selectionRec;
                    m_isFullscreen = true;
                }else{
                    m_isWindow = true;
                    auto it = mapRectToWindowId.find(m_selection->geometry());
                    if (it != mapRectToWindowId.end()) {
                        m_winId = it.value();
                    }
                    qDebug()<<"录制源 ： hover窗口 id="<<m_winId<< " 区域="<<m_selectionRec;
                }
            }else{
                qDebug()<<"录制源 ： 选择录制区域 "<<m_selectionRec;
            }
            openCameraRecord(ConfigHandler().getCameraRecord());
            if(m_camera){
                qDebug()<<"摄像头初次设置后的显示位置及大小"<< m_camera->geometry();
            }
            update();
        }else{
//            qDebug()<<"非第一次释放"; //点击工具栏；点击阴影处；移动选框和大小；
            if (m_toolBar->isHidden() && m_selection->isVisible() && m_selection->geometry().contains(m_mousePos)) {//移动选框和大小；
//                qDebug()<<"释放 - 移动选框和大小";
//                if(m_camera && m_camera->isVisible() && m_camera->geometry().contains(m_mousePos)){
//                    qDebug()<<"释放 - 移动摄像头camera和大小";
//                }

            }

        }
        //更新选区及工具栏位置
        if(m_selection->getSelectionChanged()){
            m_selectionRec = m_selection->geometry();
            updateToolBarPos(m_selection->geometry());
            m_selection->setSelectionChanged(false);
        }
        if (m_cutdown && !m_cutdown->isHidden()){
            m_toolBar->hide();
        } else {
            m_toolBar->show();
        }

        if(m_camera && m_camera->getCameraWidChanged()){
            m_camera->setCameraWidChanged(false);
        }
        //选框移动>20px时，camera位置重置
        bool isResetX = qAbs(e->pos().x() - m_dragStartPoint.x()) >20;
        bool isResetY = qAbs(e->pos().y() - m_dragStartPoint.y()) >20;
        bool isResetPos = isResetX || isResetY;
        if(m_camera && isResetPos){
            resetCameraPos();
        }

        update();

        isMousePress = false;
        isMouseRelease = true;
        isMove = false;
        isMoveCamera = false;
        isSize = false;
        isSizeCamera = false;
        isSelectOut = false;
    }

    updateCursor();
}

void CaptureWidget::keyPressEvent(QKeyEvent *e)
{
    if(!m_selection->isVisible()){
        return;
    }

    if (m_info.waylandDectected() && (m_info.windowManager() == DesktopInfo::UKUI))
    {
        if (Global::isRecordKey && m_showKeyController)
        {
            QString sKeyName = "";
            if (e->key() == Qt::Key_Shift)
            {
                sKeyName = "Shift";
            }
            else if (e->key() == Qt::Key_Control)
            {
                sKeyName = "Ctrl";
            }
            else if (e->key() == Qt::Key_CapsLock)
            {
                sKeyName = "Caps";
            }
            else
            {
                QKeySequence keySequence(e->key());
                sKeyName = keySequence.toString(QKeySequence::PortableText);;
                qDebug() << "Key Name:" << sKeyName;
            }

            m_showKeyController->showScreenkeyWindow(sKeyName);
        }
    }

    QWidget::keyPressEvent(e);
}

void CaptureWidget::resizeEvent(QResizeEvent * e)
{

}

void CaptureWidget::slotExitGui()
{
    slotCloseRecGui();
    Global::recordStatus = false;
    Controller::getInstance()->hideLeadWid();
}

void CaptureWidget::slotCloseRecGui()
{
    if(m_camera){
        openCameraRecord(false);
    }
    slotShowKey(false);
    emit captureExit(m_id);
    close();
}

void CaptureWidget::slotHideGUI()
{
    this->hide();
    if(m_camera){
        m_camera->show();   //无效，不可以单独显示
    }
}

void CaptureWidget::slotStartRec(int cutdown)
{
    if ((m_selectionRec.width()*m_scale < 30) || (m_selectionRec.height()*m_scale < 30))
    {
        slotExitGui();
        QMessageBox mes;
        mes.warning(nullptr, tr("error"), tr("The selected area is too small, please choose again"));
        QScreen *screen = QGuiApplication::primaryScreen();
        if (screen) {
            // 获取屏幕的几何信息
            QRect screenGeometry = screen->geometry();
            QSize windowSize = mes.size();
            int x = (screenGeometry.width() - windowSize.width()) / 2;
            int y = (screenGeometry.height() - windowSize.height()) / 2;
            mes.move(x/m_scale, y/m_scale);
        }
        return;
    }
    if (isWindowOutOfScreen()){
        slotExitGui();
        QMessageBox mes;
        mes.warning(nullptr, tr("error"), tr("The selected area exceeds the screen range, please choose again"));
        QScreen *screen = QGuiApplication::primaryScreen();
        if (screen) {
            // 获取屏幕的几何信息
            QRect screenGeometry = screen->geometry();
            QSize windowSize = mes.size();
            int x = (screenGeometry.width() - windowSize.width()) / 2;
            int y = (screenGeometry.height() - windowSize.height()) / 2;
            mes.move(x/m_scale, y/m_scale);
        }
        return;
    }

    if (cutdown > 0)
    {
        if (m_toolBar)
        {
            m_toolBar->hide();
        }
        m_cutdown = new CutDown(this, cutdown);
        connect(m_cutdown, &CutDown::sigCancelRec, this, &CaptureWidget::slotCancelRec);
        connect(m_cutdown, &CutDown::sigStartRec, this, &CaptureWidget::slotStartRec);
        updateCutDownPos(m_selection->geometry());
        m_cutdown->show();
    }
    else
    {
        QRect rect;
        if(m_camera && m_camera->isVisible()){
            rect = m_camera->geometry();
        }
        //关闭框选
        slotCloseRecGui();
        if (m_cutdown)
        {
            m_cutdown->hide();
        }
        //获取窗口相关信息并发送信号到core开始录制
        if(!rect.isNull()){
            Controller::getInstance()->initCameraRecorder(ConfigHandler().getCameraRecord(),rect,m_selectionRec);
        }
        Controller::getInstance()->setPropertyOfSelectWid(m_id, m_isFullscreen, m_isWindow, m_screen, m_winId, m_selectionRec, m_scale);
        bool bReturn = Controller::getInstance()->startRecord(m_winId, m_selectionRec);
        if (bReturn)
        {
            slotShowKey(Global::isRecordKey);
            checkNeedShowCursor(Global::isShowCursorClick,Global::isShowCursorPath);
        }
    }
}

void CaptureWidget::slotCancelRec()
{
    if (m_cutdown)
    {
        m_cutdown->hide();
    }
    if (m_toolBar)
    {
        m_toolBar->show();
    }

    if(!m_info.isWlcom()){
        if (m_clickAnimateControl)
        {
            m_clickAnimateControl->pointerOnOff(false);
        }
    }
}

void CaptureWidget::slotOpenSettingWid()
{
    slotExitGui();
    Controller::getInstance()->openSettingWid();
}

void CaptureWidget::slotCloseCamera()
{
    //设置界面开关 关闭摄像头
    if(m_camera){
        m_camera->stopCamera();
        delete m_camera;
        m_camera = nullptr;
    }
    if(m_button){
        delete m_button;
        m_button = nullptr;
    }
}

void CaptureWidget::openCameraRecord(bool isShow)
{
    //启用或禁用摄像头
    if(Global::recordStatus){
        if(isShow){
//            开启摄像头
            if(!m_camera){
               qDebug()<<"CaptureWidget::openCameraRecord 不存在创建";
               m_camera = new CameraPage();
               m_button = new QPushButton(this);
               m_button->setAttribute(Qt::WA_TransparentForMouseEvents);
               m_button->setFixedSize(CAMERA_BUTTON_SIZE);
               m_button->setIconSize(CAMERA_BUTTON_ICON_SIZE);
               m_button->setIcon(QIcon(":/icon/lead_close.svg"));
               m_button->setToolTip(tr("Tap Turn off camera recording"));
//               connect(m_button,&QPushButton::clicked,this,&CaptureWidget::closeCameraFromButton);
               m_button->hide();
               m_button->setStyleSheet(  QString( "QPushButton {"
                                         "   background-color: rgba(255, 255, 255, 0.85);;"   // 正常状态
                                         "   border: none;"
                                         "   border-radius: %1px;"
                                         "}" ).arg(CAMERA_BUTTON_RADIUS) );
            }
            //位置
            int distanceHeight;
            if(m_isFullscreen){
                QString schema_panel = "org.ukui.panel.settings";
                QString key_panelsize = "panelsize";
                QSettings gsettings_panel(schema_panel);
                int panelSize = gsettings_panel.value(key_panelsize, 48).toInt();
                distanceHeight = panelSize;
            }else{
                distanceHeight = CAMERA_TO_WINDOW_DISTANCE;
            }

            int x = m_selectionRec.x() + m_selectionRec.width()
                    - m_camera->width() - CAMERA_TO_WINDOW_DISTANCE;
            int y = m_selectionRec.y() + m_selectionRec.height()
                    - m_camera->height() - distanceHeight;
            m_camera->move(x,y);
            m_button->move(m_camera->geometry().right() - m_button->width()/2,
                           m_camera->geometry().top() - m_button->height()/2);
            m_button->hide();

        }else{
            qDebug()<<"CaptureWidget::openCameraRecord 需要关闭摄像头";
            //关闭录制
            if(m_camera){
                slotCloseCamera();
            }
        }
    }
}

void CaptureWidget::resetCameraPos()
{
    if(!isMoveCamera
            && !isSizeCamera && !isSelectOut){
        if(m_selectionRec.width() - CAMERA_TO_WINDOW_DISTANCE * 2  < m_camera->minimumWidth()
           || m_selectionRec.height() - CAMERA_TO_WINDOW_DISTANCE * 2 < m_camera->minimumHeight()){
            m_camera->hide();
        }else if(m_selectionRec.width() - CAMERA_TO_WINDOW_DISTANCE * 2  < CAMERA_DEFAULT_SIZE.width()
                || m_selectionRec.height() - CAMERA_TO_WINDOW_DISTANCE * 2 < CAMERA_DEFAULT_SIZE.height()){
            m_camera->resize(CAMERA_MIN_SIZE);
            m_camera->show();
        }
        else{
            m_camera->resize(CAMERA_DEFAULT_SIZE);
            m_camera->show();
        }

        int x = m_selectionRec.x() + m_selectionRec.width()
                - m_camera->width() - CAMERA_TO_WINDOW_DISTANCE;
        int y = m_selectionRec.y() + m_selectionRec.height()
                - m_camera->height() - CAMERA_TO_WINDOW_DISTANCE;
        m_camera->move(x,y);
        m_button->move(m_camera->geometry().right() - m_button->width()/2,
                       m_camera->geometry().top() - m_button->height()/2);
        m_button->hide();
  }
}

void CaptureWidget::slotUpdateCameraDisplay(bool isShow)
{
    openCameraRecord(isShow);
}

void CaptureWidget::updateMicOption(bool isEnable)
{
    if(m_toolBar){
        m_toolBar->updateMicOption(isEnable);
    }
}

void CaptureWidget::slotShowKey(bool isShowKey)
{
    if (!m_showKeyController)
    {
        m_showKeyController = new ShowkeyController(m_selectionRec, this);
    }

    m_showKeyController->showkeyReadKey(isShowKey);
}

void CaptureWidget::checkNeedShowCursor(bool isShowClick, bool isShowPath)
{
//    if(!Global::isShowCursor){
//        return;
//    }

    if(!m_info.isWlcom()){
        if (isShowClick || isShowPath)
        {
            if (!m_clickAnimateControl)
            {
                bool radiant = false;
                double opacity = 0.5;
                int showTime = 1;

                int showClickCircle = 60;
                if (m_info.isHWWayland()){
                    showClickCircle = 50;
                }

                m_clickAnimateControl = new ClickAnimateControl(showTime,
                                                                showClickCircle,
                                                                radiant,
                                                                opacity);
            }

            m_clickAnimateControl->setIsShowClick(isShowClick);
            m_clickAnimateControl->setIsShowPath(isShowPath);
            m_clickAnimateControl->pointerOnOff(true);
        }
    }else{

        if(!m_clickAnimateControl){
            m_clickAnimateControl = new ClickAnimateControl();
        }

        m_clickAnimateControl->setIsShowClick(isShowClick);
        m_clickAnimateControl->setIsShowPath(isShowPath);
    }


}

void CaptureWidget::updateCameraPos(QPoint point)
{
    QRect initialRect = m_camera->savedGeometry().normalized();
    QPoint newTopLeft = initialRect.topLeft() + (point- m_dragStartPoint);
    QRect finalRect(newTopLeft, initialRect.size());
    if (finalRect.left() < m_selection->geometry().left()) {
        qDebug()<<"1";
        finalRect.setLeft(m_selection->geometry().left());
    } else if (finalRect.right() > m_selection->geometry().right()) {
        qDebug()<<"2";
        finalRect.setLeft(m_selection->geometry().right() - m_camera->width());
    }
    if (finalRect.top() < m_selection->geometry().top()) {
        qDebug()<<"3";
        finalRect.setTop(m_selection->geometry().top());
    } else if (finalRect.bottom() > m_selection->geometry().bottom()) {
        qDebug()<<"4";
        finalRect.setBottom(m_selection->geometry().bottom());
        finalRect.setTop(m_selection->geometry().bottom() - m_camera->height());
    }
    QRect newRect = finalRect.normalized().intersected(m_selection->geometry());
    if(!m_selection->geometry().contains(newRect.bottomRight())){
        qDebug()<<"5";
        newRect.setBottomRight(m_selection->geometry().bottomRight());
    }
    m_camera->move(newRect.topLeft());
    m_button->move(m_camera->geometry().right() - m_button->width()/2,
                   m_camera->geometry().top() - m_button->height()/2);
    update();
}

void CaptureWidget::updateCameraSize(QPoint point)
{
    int minHeight = m_camera->minimumHeight();
    int maxHeight = qMin(m_camera->maximumHeight(),m_selectionRec.height()-13-13);
    int minwidth = m_camera->minimumWidth();
    int maxwidth = qMin(m_camera->maximumWidth(),m_selectionRec.width()-13-13);

    QRect r = m_camera->savedGeometry();
    QPoint offset = point - m_dragStartPoint;
    using cp = CameraPage;
    if (m_mouseOverHandleCamera == cp::TOPLEFT_SIDE
        || m_mouseOverHandleCamera == cp::TOP_SIDE
        || m_mouseOverHandleCamera == cp::TOPRIGHT_SIDE) {             // dragging one of the top handles

        int newTop = r.top() + offset.y();
        int newHeight = r.bottom() - newTop;

        if(newHeight >= maxHeight){
            r.setTop(r.bottom() - maxHeight);
        }else if(newHeight <= minHeight){
            r.setTop(r.bottom() - minHeight);
        }else{
            r.setTop(newTop);
        }

        if( r.top() <= m_selectionRec.top()){
            r.setTop(m_selectionRec.top());
        }
    }
    if (m_mouseOverHandleCamera == cp::TOPLEFT_SIDE
        || m_mouseOverHandleCamera == cp::LEFT_SIDE
        || m_mouseOverHandleCamera == cp::BOTTONLEFT_SIDE) {             // dragging one of the left handles

        int newLeft = r.left() + offset.x();
        int newWidth = r.right() - newLeft;

        if(newWidth >= maxwidth){
            r.setLeft(r.right() - maxwidth);
        }else if(newWidth <= minwidth){
            r.setLeft(r.right() - minwidth);
        }else{
            r.setLeft(newLeft);
        }

        if( r.left() <= m_selectionRec.left()){
            r.setLeft(m_selectionRec.left());
        }
    }
    if (m_mouseOverHandleCamera == cp::BOTTONLEFT_SIDE
        || m_mouseOverHandleCamera == cp::BOTTON_SIDE
        || m_mouseOverHandleCamera == cp::BOTTONRIGHT_SIDE) {             // dragging one of the bottom handles

        int newBottom = r.bottom() + offset.y();
        int newHeight = newBottom - r.top();

        if(newHeight >= maxHeight){
            r.setBottom(r.top() + maxHeight);
        }else if(newHeight <= minHeight){
            r.setBottom(r.top() + minHeight);
        }else{
            r.setBottom(newBottom);
        }

        if( r.bottom() >= m_selectionRec.bottom()){
            r.setBottom(m_selectionRec.bottom());
        }
    }
    if (m_mouseOverHandleCamera == cp::TOPRIGHT_SIDE
        || m_mouseOverHandleCamera == cp::RIGHT_SIDE
        || m_mouseOverHandleCamera == cp::BOTTONRIGHT_SIDE) {             // dragging one of the right handles
        int newRight = r.right() + offset.x();
        int newWidget = newRight - r.left();

        if(newWidget >= maxwidth){
            r.setRight(r.left() + maxwidth);
        }else if(newWidget <= minwidth){
            r.setRight(r.left() + minwidth);
        }else{
            r.setRight(newRight);
        }

        if( r.right() >= m_selectionRec.right()){
            r.setRight(m_selectionRec.right());
        }
    }
    m_camera->setGeometry(r.intersected(rect()).normalized());
    m_camera->setCameraWidChanged(true);
    m_button->move(m_camera->geometry().right() - m_button->width()/2,
                   m_camera->geometry().top() - m_button->height()/2);
    update();
}

void CaptureWidget::getWindow(WindowId windowId)
{
    WindowInfo winInfo = WindowManager::getwindowInfo(windowId);
    QString sTitle = WindowManager::getWindowTitle(windowId);

    if (!winInfo.isMinimized() &&  !sTitle.contains("desktop")  )
    {
        QRect winRect = WindowManager::windowGeometry(windowId);
        QRect rect;

        rect = QRect(winRect.x() / m_scale,
                     winRect.y() / m_scale,
                     winRect.width() / m_scale,
                     winRect.height() / m_scale);


        if (rects.count() == 0)
        {
            qDebug() << "append:" << sTitle << rect;
            rects.append(rect);
        }
        else
        {
            int insertIndex = 0;
            if ((rect.x() == 0) && (rect.y() == 0))
            {
                qDebug() << "insert:" <<insertIndex <<sTitle<< rect;
                rects.insert(insertIndex, rect);
            }
            else
            {
                qDebug() << "append:" <<sTitle<< rect;
                rects.append(rect);
            }
        }
    }
}

void CaptureWidget::slotCloseRec()
{
    if(!m_info.isWlcom()){
        if (m_clickAnimateControl)
        {
            m_clickAnimateControl->pointerOnOff(false);
        }
    }
}

void CaptureWidget::slotPauseRec()
{
    Controller::getInstance()->pauseRecord();
}

void CaptureWidget::slotContinueRec()
{
    Controller::getInstance()->contineRecord();
}

void CaptureWidget::initSelection()
{
    m_selection = new SelectionWidget(QColor(Qt::white), this);
    connect(m_selection, &SelectionWidget::animationEnded, this, [this](){
        //工具栏随选框更新位置
        updateToolBarPos(m_selection->geometry());
    });
    m_selection->setVisible(false);
    m_selection->setGeometry(QRect());
}

void CaptureWidget::updateCursor()
{
    using sw = SelectionWidget;
    //初始十字，首次按压/释放进行选框双箭头，在选框手型-按下握拳，选框四角箭头
    if (!isfirstPress) {
        setCursor(Qt::CrossCursor); //十字
    }else {
        if(m_camera && m_button->geometry().contains(m_mousePos) ){
            setCursor(Qt::ArrowCursor);
        }
        else if (m_mouseOverHandle != sw::NO_SIDE) {
            // cursor on the handlers
            switch (m_mouseOverHandle) {
            case sw::TOPLEFT_SIDE:
            case sw::BOTTONRIGHT_SIDE:
                setCursor(Qt::SizeFDiagCursor);
                break;
            case sw::TOPRIGHT_SIDE:
            case sw::BOTTONLEFT_SIDE:
                setCursor(Qt::SizeBDiagCursor);
                break;
            case sw::LEFT_SIDE:
            case sw::RIGHT_SIDE:
                setCursor(Qt::SizeHorCursor);
                break;
            case sw::TOP_SIDE:
            case sw::BOTTON_SIDE:
                setCursor(Qt::SizeVerCursor);
                break;
            default:
                break;
            }
        }
        else if(m_camera && m_selection->isVisible()
                && m_mouseOverHandleCamera != CameraPage::NO_SIDE
                ){
            switch (m_mouseOverHandleCamera) {
            case CameraPage::TOPLEFT_SIDE:
            case CameraPage::BOTTONRIGHT_SIDE:
                setCursor(Qt::SizeFDiagCursor);
                break;
            case CameraPage::TOPRIGHT_SIDE:
            case CameraPage::BOTTONLEFT_SIDE:
                setCursor(Qt::SizeBDiagCursor);
                break;
            case CameraPage::LEFT_SIDE:
            case CameraPage::RIGHT_SIDE:
                setCursor(Qt::SizeHorCursor);
                break;
            case CameraPage::TOP_SIDE:
            case CameraPage::BOTTON_SIDE:
                setCursor(Qt::SizeVerCursor);
                break;
            default:
                break;
            }
        }
        else if(m_selection->isVisible() && isMousePress && m_selection->geometry().contains(m_mousePos)){
            setCursor(Qt::ClosedHandCursor); //握拳
            //鼠标首次按压进行选框
            if(isfirstPress && !isfirstRelease){
                setCursor(Qt::SizeFDiagCursor); //双箭头
            }
        }else if(m_selection->isVisible() && isMouseRelease && m_selection->geometry().contains(m_mousePos)){
            setCursor(Qt::OpenHandCursor); //手型
            //鼠标首次释放选框完成
            m_mouseOverHandle = m_selection->getMouseSide(m_mousePos);
            if( m_mouseOverHandle == sw::BOTTONRIGHT_SIDE){
                setCursor(Qt::SizeFDiagCursor);
            }
        }else{
            setCursor(Qt::ArrowCursor);
        }
    }
}

void CaptureWidget::initConnect()
{
    connect(m_toolBar, &ToolBar::sigCloseRecGui, this, &CaptureWidget::slotCloseRecGui);
    connect(m_toolBar, &ToolBar::sigStartRec, this, &CaptureWidget::slotStartRec);
    connect(m_toolBar, &ToolBar::sigOpenSettingWid,this, &CaptureWidget::slotOpenSettingWid);
    connect(m_toolBar, &ToolBar::sigShowKey, this, &CaptureWidget::slotShowKey);
    connect(this, &CaptureWidget::sigStartFromToolbar, m_toolBar, &ToolBar::start);
    new QShortcut(Qt::Key_Escape, this, SLOT(slotExitGui()));
}

void CaptureWidget::updateCrosspixmap(QPoint e)
{

}


void CaptureWidget::updateToolBarPos(const QRect &selection)
{
    m_buttonBaseSize = 36;
    m_RectSelection = intersectWithAreas(selection);    //内部修改选择区域的副本
    updateBlockedSides();                               //更新矩形区域的阻挡状态
    ensureSelectionMinimunSize();                       //检测选框的大小

    QPoint leftTop;
    if (m_allSidesBlocked) { //在里面
//        qDebug()<<"--------- 里面 ----------";
        //移动到选框中心偏上
        leftTop = QPoint(m_RectSelection.x() + (m_RectSelection.width()-m_toolBar->width())/2,
                         m_RectSelection.y() + toolbarSelectionMargin);

    }else if (!m_blockedBottom) { //默认在选框的下面
//        qDebug()<<"--------- 下面 ----------";
        leftTop = QPoint(m_RectSelection.x() + (m_RectSelection.width()-m_toolBar->width())/2,
                         m_RectSelection.y() + m_RectSelection.height() + toolbarSelectionMargin);
        //左(右)边触边
        QPoint pointA(leftTop.x() - toolbarSelectionMargin,leftTop.y() );
        QPoint pointB(leftTop.x() + m_toolBar->width() + toolbarSelectionMargin,leftTop.y() );
        if(!m_buttonCurScreen.contains(pointA)){
            leftTop.setX(m_buttonCurScreen.x() + toolbarSelectionMargin);
        }
        if(!m_buttonCurScreen.contains(pointB)){
           leftTop.setX(m_buttonCurScreen.x() + m_buttonCurScreen.width() - toolbarSelectionMargin - m_toolBar->width());
        }

    }else if(m_blockedBottom && !m_blockedTop){ //在选框上面
//        qDebug()<<"--------- 上面 ----------";
        leftTop = QPoint(m_RectSelection.x() + (m_RectSelection.width()-m_toolBar->width())/2,
                         m_RectSelection.y() - toolbarSelectionMargin - m_toolBar->height() );

        //左(右)边触边
        QPoint pointA(leftTop.x() - toolbarSelectionMargin,leftTop.y() );
        QPoint pointB(leftTop.x() + m_toolBar->width() + toolbarSelectionMargin,leftTop.y() );
        if(!m_buttonCurScreen.contains(pointA)){
            leftTop.setX(m_buttonCurScreen.x() + toolbarSelectionMargin);
        }
        if(!m_buttonCurScreen.contains(pointB)){
           leftTop.setX(m_buttonCurScreen.x() + m_buttonCurScreen.width() - toolbarSelectionMargin - m_toolBar->width());
        }

    }else if(m_blockedBottom && m_blockedTop && !m_blockedRight){ //在选框的右边
//        qDebug()<<"--------- 右边 ----------";
        leftTop = QPoint(m_RectSelection.right() + toolbarSelectionMargin,
                         m_RectSelection.y() + (m_RectSelection.height()-m_toolBar->height())/2 );

    }else{ //在选框的左边  选框最小大小
//        qDebug()<<"--------- 左边 ----------";
            leftTop = QPoint(m_RectSelection.x() - toolbarSelectionMargin - m_toolBar->width(),
                             m_RectSelection.y() + (m_RectSelection.height()-m_toolBar->height())/2 );
    }

    m_toolBar->move(leftTop);
}

QRect CaptureWidget::intersectWithAreas(const QRect &rect)
{
    QRect res;
    for (const QRect &r : areas) {
        QRect temp = rect.intersected(r);
        if (temp.height() * temp.width() >= res.height() * res.width()) {
            res = temp;
            m_buttonCurScreen = r;
        }
    }
    return res;
}

void CaptureWidget::updateBlockedSides()
{
    const int EXTENSION_V =  m_toolBar->height() + toolbarSelectionMargin * 2;  //工具栏在选框上(下)的扩展距离：工具栏的高+工具栏距选框和屏幕边界的距离
    const int EXTENSIONS_H = m_toolBar->width() + toolbarSelectionMargin * 2 ;  //
    QPoint pointA,pointB;

    // Bottom
    pointA = QPoint(m_RectSelection.left(),
                    m_RectSelection.bottom() + EXTENSION_V);
    pointB = QPoint(m_RectSelection.right(),
                    pointA.y());
    m_blockedBottom = !(m_buttonCurScreen.contains(pointA)
                        && m_buttonCurScreen.contains(pointB));
    // Top
    pointA.setY(m_RectSelection.top() - EXTENSION_V);
    pointB.setY(pointA.y());
    m_blockedTop = !(m_buttonCurScreen.contains(pointA)
                     && m_buttonCurScreen.contains(pointB));
    // Right
    pointA = QPoint(m_RectSelection.right() + EXTENSIONS_H, m_RectSelection.bottom());
    pointB = QPoint(pointA.x(), m_RectSelection.top());
    m_blockedRight = !(m_buttonCurScreen.contains(pointA)
                       && m_buttonCurScreen.contains(pointB));
    // Left
    pointA.setX(m_RectSelection.left() - EXTENSIONS_H);
    pointB.setX(pointA.x());
    m_blockedLeft = !(m_buttonCurScreen.contains(pointA)
                      && m_buttonCurScreen.contains(pointB));

    m_allSidesBlocked = ( m_blockedBottom && m_blockedTop  && m_blockedRight && m_blockedLeft );
}

void CaptureWidget::ensureSelectionMinimunSize()
{
    if (m_RectSelection.width() < m_buttonBaseSize) {
        m_RectSelection.setWidth(m_buttonBaseSize);
    }
    if (m_RectSelection.height() < m_buttonBaseSize) {
        m_RectSelection.setHeight(m_buttonBaseSize);
    }
}

void CaptureWidget::updateScreenRegions()
{
    for (QScreen * const screen : QGuiApplication::screens()) {
        QRect r = QRect(screen->geometry());
        areas.append(r);
    }
}

void CaptureWidget::updateSelectionBorder(QPainter &painter)
{
    if (!m_toolBar->isVisible() && m_cutdown && m_cutdown->isHidden()) {
        return;
    }

    QRect r = m_selection->geometry().normalized().adjusted(0, 0, -1, -1);

    painter.setPen(QColor(255, 255, 255));
    painter.setOpacity(1);

    // 绘制截图选择区域矩形边框的四条边
    painter.drawLine(r.topLeft(), r.bottomLeft());
    painter.drawLine(r.topLeft(), r.topRight());
    painter.drawLine(r.bottomRight(), r.topRight());
    painter.drawLine(r.bottomRight(), r.bottomLeft());

    // 绘制截图选择区域矩形边框的四条边上的实心圆圈
    updateSelectionControlPoint(painter);

    return;
}

void CaptureWidget::updateSelectionControlPoint(QPainter &painter)
{
    painter.setBrush(QColor(160, 160, 160));
    painter.setPen(QColor(255, 255, 255));
    for (auto r: m_selection->handlerAreas()) {
        painter.drawRoundedRect(r, r.width()/2, r.height()/2, Qt::AbsoluteSize);
        painter.drawPixmap(r, QPixmap(QStringLiteral(":/icon/control_point.svg")));
    }

    return;
}

void CaptureWidget::updateSizeLabelOption()
{
    auto screenNumber = QApplication::desktop()->screenNumber();
    QScreen *screen = QApplication::screens()[screenNumber];
    size_label->setText(tr("%1 * %2")
                        .arg(qRound(m_selection->geometry().intersected(rect()).width()*screen->devicePixelRatio()))
                        .arg(qRound(m_selection->geometry().intersected(rect()).height()*screen->devicePixelRatio())));

    QPoint  point(m_selection->geometry().x(),
                  m_selection->geometry().y() - toolbarSelectionMargin - size_label->height());
    if(!m_buttonCurScreen.contains(point)){
        point.setY(m_selection->geometry().y());
    }
    size_label->move(point);
    size_label->show();
}

void CaptureWidget::updateCutDownPos(const QRect &selection)
{
    m_buttonBaseSize = 36;
    m_RectSelection = intersectWithAreas(selection);    //内部修改选择区域的副本
    updateBlockedSides();                               //更新矩形区域的阻挡状态
    ensureSelectionMinimunSize();                       //检测选框的大小

    QPoint leftTop;
    if (m_allSidesBlocked) { //在里面
//        qDebug()<<"--------- 里面 ----------";
        //移动到选框中心偏上
        leftTop = QPoint(m_RectSelection.x() + (m_RectSelection.width()-m_cutdown->width())/2,
                         m_RectSelection.y() + toolbarSelectionMargin);

    }else if (!m_blockedBottom) { //默认在选框的下面
//        qDebug()<<"--------- 下面 ----------";
        leftTop = QPoint(m_RectSelection.x() + (m_RectSelection.width()-m_cutdown->width())/2,
                         m_RectSelection.y() + m_RectSelection.height() + toolbarSelectionMargin);
        //左(右)边触边
        QPoint pointA(leftTop.x() - toolbarSelectionMargin,leftTop.y() );
        QPoint pointB(leftTop.x() + m_cutdown->width() + toolbarSelectionMargin,leftTop.y() );
        if(!m_buttonCurScreen.contains(pointA)){
            leftTop.setX(m_buttonCurScreen.x() + toolbarSelectionMargin);
        }
        if(!m_buttonCurScreen.contains(pointB)){
           leftTop.setX(m_buttonCurScreen.x() + m_buttonCurScreen.width() - toolbarSelectionMargin - m_cutdown->width());
        }

    }else if(m_blockedBottom && !m_blockedTop){ //在选框上面
//        qDebug()<<"--------- 上面 ----------";
        leftTop = QPoint(m_RectSelection.x() + (m_RectSelection.width()-m_cutdown->width())/2,
                         m_RectSelection.y() - toolbarSelectionMargin - m_cutdown->height() );

        //左(右)边触边
        QPoint pointA(leftTop.x() - toolbarSelectionMargin,leftTop.y() );
        QPoint pointB(leftTop.x() + m_cutdown->width() + toolbarSelectionMargin,leftTop.y() );
        if(!m_buttonCurScreen.contains(pointA)){
            leftTop.setX(m_buttonCurScreen.x() + toolbarSelectionMargin);
        }
        if(!m_buttonCurScreen.contains(pointB)){
           leftTop.setX(m_buttonCurScreen.x() + m_buttonCurScreen.width() - toolbarSelectionMargin - m_cutdown->width());
        }

    }else if(m_blockedBottom && m_blockedTop && !m_blockedRight){ //在选框的右边
//        qDebug()<<"--------- 右边 ----------";
        leftTop = QPoint(m_RectSelection.right() + toolbarSelectionMargin,
                         m_RectSelection.y() + (m_RectSelection.height()-m_cutdown->height())/2 );

    }else{ //在选框的左边  选框最小大小
//        qDebug()<<"--------- 左边 ----------";
            leftTop = QPoint(m_RectSelection.x() - toolbarSelectionMargin - m_cutdown->width(),
                             m_RectSelection.y() + (m_RectSelection.height()-m_cutdown->height())/2 );
    }

    m_cutdown->move(leftTop);
}

bool CaptureWidget::isWindowOutOfScreen(){
    QScreen *screen = QGuiApplication::primaryScreen();
    if(screen){
        QRect full_Rect = screen->virtualGeometry();
        if(m_selectionRec.x() < full_Rect.x() ||
           m_selectionRec.y() < full_Rect.y() ||
           m_selectionRec.right() > full_Rect.right() ||
           m_selectionRec.bottom() > full_Rect.bottom()){
            return true;
        }
    }
    return false;
}
